package com.example.bankend.service.method;

import com.example.bankend.model.chatmessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ChatService {
//    @Value("${volcengine.api-key}")
    private String apiKey = "882d1658-5688-4325-8393-4d6d59c31567";


    private final ArkService arkService;

    public ChatService() {
        ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
        Dispatcher dispatcher = new Dispatcher();
        this.arkService = ArkService.builder()
                .timeout(Duration.ofSeconds(1800))
                .connectTimeout(Duration.ofSeconds(20))
                .dispatcher(dispatcher)
                .connectionPool(connectionPool)
                .baseUrl("https://ark.cn-beijing.volces.com/api/v3")
                .apiKey(apiKey)
                .build();
    }

    public chatmessage getResponseFromAi(chatmessage userMessage) {
        final List<com.volcengine.ark.runtime.model.completion.chat.ChatMessage> messages = new ArrayList<>();
        final com.volcengine.ark.runtime.model.completion.chat.ChatMessage aiMessage = com.volcengine.ark.runtime.model.completion.chat.ChatMessage.builder()
                .role(ChatMessageRole.USER)
                .content(userMessage.getContent())
                .build();
        messages.add(aiMessage);

        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model("deepseek-r1-250528")
                .messages(messages)
                .build();

        String responseContent = (String) arkService.createChatCompletion(chatCompletionRequest)
                .getChoices()
                .stream()
                .map(choice -> choice.getMessage().getContent())
                .findFirst()
                .orElse("No response from model");

        return new chatmessage(responseContent, "ai");
    }

    public void saveUserMessage(chatmessage userMessage) {
        // 实现保存用户消息的逻辑，例如保存到数据库
    }

    public List<chatmessage> getAllChatHistory() {
        // 实现获取所有对话历史的逻辑，例如从数据库查询
        return new ArrayList<>();
    }
}